package com.itheima.service;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

//将类交给spring管理,为了后面调用(也可以通过配置文件注入)
@Component
public class SpringSecurityUserService  implements UserDetailsService {
    //远程调用数据库中的用户信息
    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.itheima.pojo.User user = userService.findByUsername(username);
        if (user==null) {
            //用户名不存在
            return null;//返回null表示验证不通过
        }
        //sc的返回值的第三个参数,是当前用户的权限集合
        List<GrantedAuthority> list=new ArrayList<>();
        //动态为当前用户授权
        //查询点给钱用户的角色
        Set<Role> roles = user.getRoles();
        //遍历角色获取当前角色对应的权限
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));//添加角色关键字
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
              list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        org.springframework.security.core.userdetails.User securityUser =new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return securityUser;
    }
}
